import React, { useState, useMemo } from 'react';
import {
    Table, InputNumber, Select, Button,
    Modal, Form, Tag, Card, Row, Col, Typography, Input
} from 'antd';
import { ExportOutlined } from '@ant-design/icons';

const { Title } = Typography;
const { Option } = Select;

// 模拟材料数据
const mockMaterials = [
    {
        id: 1,
        code: 'MAT-001',
        name: '钢筋',
        specification: 'HRB400',
        brand: '宝钢',
        supplier: '建材供应商A',
        project: 1,
        warehouse: 101,
        type: '建筑材料',
        amount: 5000,
        cost: 2800,
        unit: '吨',
        rate: 0.13,
        beginning_amount: 100,
        existing_amount: 85,
        loss_amount: 5,
        outbound_amount: 10,
        purchaseTime: '2023-05-15',
        paymentTime: '2023-06-01',
        status: '在库',
        purchaser: '张三',
        remark: '高强度螺纹钢'
    },
    {
        id: 2,
        code: 'MAT-002',
        name: '水泥',
        specification: 'P.O42.5',
        brand: '海螺',
        supplier: '建材供应商B',
        project: 1,
        warehouse: 101,
        type: '建筑材料',
        amount: 10000,
        cost: 3200,
        unit: '吨',
        rate: 0.13,
        beginning_amount: 200,
        existing_amount: 180,
        loss_amount: 10,
        outbound_amount: 10,
        purchaseTime: '2023-06-10',
        paymentTime: '2023-06-25',
        status: '在库',
        purchaser: '李四',
        remark: '普通硅酸盐水泥'
    },
    {
        id: 3,
        code: 'MAT-003',
        name: '砂石',
        specification: '中砂',
        brand: '天然',
        supplier: '建材供应商C',
        project: 1,
        warehouse: 101,
        type: '建筑材料',
        amount: 8000,
        cost: 1500,
        unit: '立方米',
        rate: 0.13,
        beginning_amount: 300,
        existing_amount: 250,
        loss_amount: 20,
        outbound_amount: 30,
        purchaseTime: '2023-06-20',
        paymentTime: '2023-07-05',
        status: '在库',
        purchaser: '王五',
        remark: '建筑用砂'
    },
    {
        id: 4,
        code: 'MAT-004',
        name: '电线',
        specification: 'BV2.5mm²',
        brand: '远东',
        supplier: '电气供应商A',
        project: 2,
        warehouse: 102,
        type: '电气材料',
        amount: 10000,
        cost: 4500,
        unit: '卷',
        rate: 0.13,
        beginning_amount: 200,
        existing_amount: 150,
        loss_amount: 10,
        outbound_amount: 40,
        purchaseTime: '2023-05-20',
        paymentTime: '2023-06-05',
        status: '在库',
        purchaser: '赵六',
        remark: '铜芯聚氯乙烯绝缘电线'
    },
    {
        id: 5,
        code: 'MAT-005',
        name: 'PVC管',
        specification: 'Φ110mm',
        brand: '联塑',
        supplier: '管材供应商A',
        project: 3,
        warehouse: 103,
        type: '管材',
        amount: 5000,
        cost: 3800,
        unit: '米',
        rate: 0.13,
        beginning_amount: 1000,
        existing_amount: 800,
        loss_amount: 50,
        outbound_amount: 150,
        purchaseTime: '2023-07-01',
        paymentTime: '2023-07-15',
        status: '在库',
        purchaser: '钱七',
        remark: '排水用硬聚氯乙烯管材'
    }
];

const destinationOptions = [
    { value: 'use', label: '使用' },
    { value: 'consume', label: '消耗' },
    { value: 'transfer', label: '移仓' },
    { value: 'rent', label: '租借' },
    { value: 'sale', label: '出售' },
    { value: 'loss', label: '损耗' }
];

const OutboundManagement = () => {
    const [form] = Form.useForm();
    const [materials, setMaterials] = useState(mockMaterials);
    const [selectedRows, setSelectedRows] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [filters, setFilters] = useState({
        name: '',
        brand: '',
        status: ''
    });

    // 筛选后的数据
    const filteredMaterials = useMemo(() => {
        return materials.filter(item => {
            return (
                (!filters.name || item.name.includes(filters.name)) &&
                (!filters.brand || item.brand.includes(filters.brand)) &&
                (!filters.status || item.status === filters.status)
            );
        });
    }, [materials, filters]);

    // 数量变化
    const handleQuantityChange = (id, value) => {
        setMaterials(prev =>
            prev.map(item =>
                item.id === id ? { ...item, outboundQuantity: value } : item
            )
        );
        setSelectedRows(prev =>
            prev.map(row =>
                row.id === id ? { ...row, outboundQuantity: value } : row
            )
        );
    };

    // 去向变化
    const handleDestinationChange = (id, value) => {
        setMaterials(prev =>
            prev.map(item =>
                item.id === id ? { ...item, destination: value } : item
            )
        );
        setSelectedRows(prev =>
            prev.map(row =>
                row.id === id ? { ...row, destination: value } : row
            )
        );
    };

    // 行选择
    const rowSelection = {
        onChange: (_, selected) => {
            const rowsWithProps = selected.map(row => ({
                ...row,
                outboundQuantity: row.outboundQuantity || 1,
                destination: row.destination || 'use'
            }));
            setSelectedRows(rowsWithProps);
        }
    };

    const handleSubmit = () => {
        if (selectedRows.length === 0) {
            Modal.error({
                title: '出库操作失败',
                content: '请至少选择一项材料进行出库操作'
            });
            return;
        }
        const invalidRows = selectedRows.filter(
            row => row.outboundQuantity <= 0 || row.outboundQuantity > row.existing_amount
        );
        if (invalidRows.length > 0) {
            Modal.error({
                title: '出库数量错误',
                content: (
                    <div>
                        <p>以下材料的出库数量无效：</p>
                        <ul>
                            {invalidRows.map(row => (
                                <li key={row.id}>
                                    {row.name}：出库数量不能为0或超过当前库存({row.existing_amount})
                                </li>
                            ))}
                        </ul>
                    </div>
                )
            });
            return;
        }
        setIsModalVisible(true);
    };

    const handleConfirmOutbound = () => {
        Modal.success({
            title: '出库操作成功',
            content: `已成功提交 ${selectedRows.length} 项材料的出库请求`
        });
        setIsModalVisible(false);
    };

    const columns = [
        { title: '材料编码', dataIndex: 'code', key: 'code', width: 120 },
        { title: '材料名称', dataIndex: 'name', key: 'name', width: 150 },
        { title: '规格型号', dataIndex: 'specification', key: 'specification', width: 120 },
        { title: '品牌', dataIndex: 'brand', key: 'brand', width: 120 },
        {
            title: '当前库存',
            dataIndex: 'existing_amount',
            key: 'existing_amount',
            width: 110,
            render: (text, record) => `${text} ${record.unit}`
        },
        {
            title: '出库数量',
            key: 'outboundQuantity',
            width: 140,
            render: (_, record) => (
                <InputNumber
                    min={1}
                    max={record.existing_amount}
                    value={record.outboundQuantity || 1}
                    onChange={value => handleQuantityChange(record.id, value)}
                    style={{ width: '100%' }}
                />
            )
        },
        {
            title: '出库去向',
            key: 'destination',
            width: 150,
            render: (_, record) => (
                <Select
                    value={record.destination || 'use'}
                    style={{ width: '100%' }}
                    onChange={value => handleDestinationChange(record.id, value)}
                >
                    {destinationOptions.map(opt => (
                        <Option key={opt.value} value={opt.value}>
                            {opt.label}
                        </Option>
                    ))}
                </Select>
            )
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: status => (
                <Tag color={status === '在库' ? 'green' : 'volcano'}>{status}</Tag>
            )
        }
    ];

    const totalQuantity = selectedRows.reduce(
        (sum, row) => sum + (row.outboundQuantity || 0),
        0
    );

    return (
        <div style={{ padding: 20, maxWidth: 1400,}}>
            <Card style={{ marginBottom: 20 }}>
                <Row gutter={16} align="middle">
                    <Col span={16}>
                        <Input
                            placeholder="材料名称"
                            style={{ width: 180, marginRight: 10 }}
                            value={filters.name}
                            onChange={e =>
                                setFilters(prev => ({ ...prev, name: e.target.value }))
                            }
                        />
                        <Input
                            placeholder="品牌"
                            style={{ width: 180, marginRight: 10 }}
                            value={filters.brand}
                            onChange={e =>
                                setFilters(prev => ({ ...prev, brand: e.target.value }))
                            }
                        />
                        <Select
                            placeholder="状态"
                            allowClear
                            style={{ width: 150 }}
                            value={filters.status}
                            onChange={value =>
                                setFilters(prev => ({ ...prev, status: value }))
                            }
                        >
                            <Option value="在库">在库</Option>
                            <Option value="出库">出库</Option>
                        </Select>
                    </Col>
                </Row>
            </Card>
            <div style={{ display: 'flex', }}>
                    <Card title="材料列表">
                        <Table
                            rowKey="id"
                            columns={columns}
                            style={{ width: 'calc(100vw - 128px - 360px - 48px)',}}
                            dataSource={filteredMaterials}
                            rowSelection={{ type: 'checkbox', ...rowSelection }}
                            pagination={{
                                pageSize: 5,
                                showSizeChanger: false,
                                showTotal: total => `共 ${total} 条记录`
                            }}
                            scroll={{ x: 'max-content' }}
                        />
                    </Card>
                {/* 右侧常驻面板 */}
                <div
                    style={{
                        position: 'fixed',
                        // flex: '3',
                        // position: 'sticky', // 页面滚动时固定
                        top: 72,
                        right: 0,
                        height: 'calc(100vh - 72px)',
                        minWidth: 250,
                        maxWidth: 350,
                        backgroundColor: '#fff',
                        boxShadow: '0 0 8px rgba(0,0,0,0.15)',
                        display: 'flex',
                        flexDirection: 'column',
                        padding: '16px',
                        overflowY: 'auto',
                        zIndex: 100
                    }}
                >
                    <Title level={5}>已选材料</Title>
                    {selectedRows.length === 0 ? (
                        <div style={{ textAlign: 'center', marginTop: 50, color: '#999' }}>
                            暂无选中材料
                        </div>
                    ) : (
                        <>
                            {selectedRows.map((row, index) => (
                                <div
                                    key={row.id}
                                    style={{
                                        padding: '20px',
                                        borderBottom: '1px solid #f0f0f0',
                                        backgroundColor: index % 2 === 0 ? '#f9f9f9' : 'white'
                                    }}
                                >
                                    <strong>{row.name}</strong> ({row.code} | {row.specification})
                                    <div>品牌: {row.brand}</div>
                                    <div>库存: {row.existing_amount} {row.unit}</div>
                                    <div>出库数量: <Tag color="blue" size = "small">{row.outboundQuantity} {row.unit}</Tag></div>
                                    <div>去向: <Tag color="geekblue" size = "small">
                                        {destinationOptions.find(opt => opt.value === row.destination)?.label}
                                    </Tag></div>
                                </div>
                            ))}
                            <div style={{ marginTop: 20, textAlign: 'center' }}>
                                <Title level={5}>出库摘要</Title>
                                <p>已选材料: <strong>{selectedRows.length}</strong> 种</p>
                                <p>总出库数量: <strong>{totalQuantity}</strong></p>
                                <Button
                                    type="primary"
                                    icon={<ExportOutlined />}
                                    onClick={handleSubmit}
                                >
                                    确认出库
                                </Button>
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* 确认模态框 */}
            <Modal
                title="确认出库信息"
                open={isModalVisible}
                onOk={handleConfirmOutbound}
                onCancel={() => setIsModalVisible(false)}
                okText="确认出库"
                cancelText="取消"
                width={800}
            >
                <div style={{ maxHeight: 400, overflowY: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                        <tr style={{ backgroundColor: '#f5f5f5' }}>
                            <th style={{ padding: 10 }}>材料名称</th>
                            <th style={{ padding: 10, textAlign: 'center' }}>规格</th>
                            <th style={{ padding: 10, textAlign: 'center' }}>数量</th>
                            <th style={{ padding: 10, textAlign: 'center' }}>去向</th>
                        </tr>
                        </thead>
                        <tbody>
                        {selectedRows.map(row => (
                            <tr key={row.id}>
                                <td style={{ padding: 10 }}>{row.name}</td>
                                <td style={{ padding: 10, textAlign: 'center' }}>{row.specification}</td>
                                <td style={{ padding: 10, textAlign: 'center' }}>
                                    <Tag color="blue">{row.outboundQuantity} {row.unit}</Tag>
                                </td>
                                <td style={{ padding: 10, textAlign: 'center' }}>
                                    <Tag color="geekblue">{destinationOptions.find(opt => opt.value === row.destination)?.label}</Tag>
                                </td>
                            </tr>
                        ))}
                        </tbody>
                    </table>
                </div>
                <div style={{ marginTop: 20, textAlign: 'center' }}>
                    <p>总计: <strong>{selectedRows.length}</strong> 种材料, <strong>{totalQuantity}</strong> 单位数量</p>
                </div>
            </Modal>
        </div>
    );
};

export default OutboundManagement;
